package server;

import java.io.IOException;
import java.util.MissingResourceException;
import java.util.Timer;

import message.Response;
import message.response.MessageResponse;
import util.Config;
import cli.Command;
import cli.Shell;

public class FileServerCli implements IFileServerCli {

	private FileServer fileserver;

	private Shell shell;
	private Thread shellThread;
	private ClientDispatcher dispatcher;
	private Timer timer;
	private Config messages;

	public FileServerCli(FileServer fs, Shell shell) {
		fileserver = fs;
		this.shell = shell;
		this.shell.register(this);
		
		shellThread = new Thread(this.shell, "ShellThread");
		messages = new Config("messages");
		dispatcher = new ClientDispatcher(fileserver);
		timer = new Timer();

		ProxyNotifier notifier = new ProxyNotifier(fileserver.getProxyHost(), fileserver.getProxyUdpPort(),
				fileserver.getAliveMessage());

		timer.schedule(notifier, 0, fileserver.getAlivePeriod());
		shellThread.start();
		dispatcher.start();
	}
	
	@Command
	public Response list() throws IOException {
		return fileserver.versionList();
	}

	@Override
	@Command
	public MessageResponse exit() throws IOException {

		shellThread.interrupt();
		shell.close();
		System.in.close();
		timer.cancel();
		dispatcher.shutdown();

		return new MessageResponse(messages.getString("info.shutdown"));
	}

	public static void main(String[] args) {

		int serverID = Integer.parseInt(args[0]);

		try {
			Config config = new Config("fs" + serverID);
			Shell shell = new Shell("FileServer" + serverID, System.out,
					System.in);

			FileServer fileserver = new FileServer(config);

			new FileServerCli(fileserver, shell);
		} catch (MissingResourceException e) {
			System.out.println("Error: Fileserver" + serverID
					+ " could not start, missing resources.");
		}
	}
}
